﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YasharEl.Infrastructure.EntityModel;

namespace YasharEl.Infrastructure.Core.EntityModel.Prototype
{
    public class DateTimeValueConverter : AbstractDataTypeValueConverter
    {
        private readonly IDateTimeProvider dateTimeProvider;

        public DateTimeValueConverter(IDateTimeProvider dateTimeProvider)
        {
            Contract.Requires<ArgumentNullException>(dateTimeProvider != null, "dateTimeProvider could not be null.");

            this.dateTimeProvider = dateTimeProvider;
        }


        public override object UnwrapRealValue(object value)
        {
            if (value == null)
                return null;
            if (value is DateTime)
                return value;
            if ((value is string) && string.IsNullOrEmpty(value as string))
                return null;

            return dateTimeProvider.Parse(value as string);
        }

        public override string WrapValue(object value)
        {
            if (value == null)
                return null;
            if (value is string)
            {
                if (string.IsNullOrEmpty((value as string)))
                    return null;
            }

            return dateTimeProvider.Parse(dateTimeProvider.Parse(value.ToString()));
        }

        public override bool HasValue(object value)
        {
            if (value == null)
                return false;
            if (value is string)
            {
                if (string.IsNullOrEmpty((value as string)))
                    return false;
            }

            return true;
        }

        public override bool IsValid(object value)
        {
            if (!HasValue(@value))
                return false;
            if (value is DateTime)
                return true;
            return base.IsValid(value);
        }
    }
}
